package com.example.xyr.myapplication.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.example.xyr.myapplication.Constant;
import com.example.xyr.myapplication.MyApp;
import com.example.xyr.myapplication.R;
import com.example.xyr.myapplication.base.BaseActivity;
import com.example.xyr.myapplication.model.FriendMsgLite;
import com.example.xyr.myapplication.service.LatlonService;
import com.example.xyr.myapplication.ui.im.ChatActivity;
import com.example.xyr.myapplication.ui.im.ChatUserUtils;
import com.example.xyr.myapplication.ui.im.RpUserAvatar;
import com.example.xyr.myapplication.utils.ActivityManger;
import com.example.xyr.myapplication.utils.BitmapUtils;
import com.example.xyr.myapplication.utils.DateUtils;
import com.example.xyr.myapplication.utils.JrmfSignUtil;
import com.example.xyr.myapplication.utils.LatlonUtils;
import com.example.xyr.myapplication.utils.LogUtil;
import com.example.xyr.myapplication.utils.MyIntent;
import com.example.xyr.myapplication.utils.PermissionUtils;
import com.example.xyr.myapplication.utils.PoputWindowUtils;
import com.example.xyr.myapplication.utils.ResourceLink;
import com.example.xyr.myapplication.utils.StringUtil;
import com.example.xyr.myapplication.view.HeartFaomThread;
import com.example.xyr.myapplication.view.HeartView;
import com.example.xyr.myapplication.view.PeriscopeLayout;
import com.example.xyr.myapplication.viewexplosion.ExplosionField;
import com.example.xyr.myapplication.viewexplosion.factory.FallingParticleFactory;
import com.jrmf360.tools.JrmfClient;
import com.jrmf360.tools.utils.ToastUtil;
import com.squareup.picasso.Picasso;

import java.util.List;

import butterknife.BindView;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.event.ChatRoomMessageEvent;
import cn.jpush.im.android.api.event.ContactNotifyEvent;
import cn.jpush.im.android.api.event.LoginStateChangeEvent;
import cn.jpush.im.android.api.model.UserInfo;

public class MainActivity extends BaseActivity implements View.OnClickListener {


    @BindView(R.id.main_tv)
    TextView mainTv;
    @BindView(R.id.main_tv1)
    TextView mainTv1;
    @BindView(R.id.main_heartview)
    HeartView mainHeartview;
    @BindView(R.id.main_iv_background)
    ImageView ivBackground;
    @BindView(R.id.main_layout_bottom)
    LinearLayout llyBottom;
    @BindView(R.id.main_bottom_chat)
    LinearLayout bottomChat;
    @BindView(R.id.main_bottom_user)
    LinearLayout bottomUser;
    @BindView(R.id.main_bottom_friend)
    LinearLayout bottomFriend;
    @BindView(R.id.main_bottom_map)
    LinearLayout bottomMap;
    @BindView(R.id.main_heard_faom)
    PeriscopeLayout heardFaom;


    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    setLoveTime();
                    break;
                case 2:
                    loadImage();
                    if (handler != null) {
                        handler.sendEmptyMessageDelayed(2, 5000);
                    }
                    break;
                case 3:
                    simulationClick();
                    break;
                case 4:
                    getOtherInfo();
                    break;
            }
        }
    };
    private ExplosionField explosionField;
    private Animation animtv;
    private String userId;
    private String otherUid;
    public static String otherNickName;
    public static String otherAddress;
    private boolean recordPermission;
    private boolean locationPermission;
    private boolean sdPermission;


    @Override
    public int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void init() {
        //动画
        explosionField = new ExplosionField(this, new FallingParticleFactory());
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.heartanim);
        mainHeartview.setAnimation(animation);
        handler.sendEmptyMessageDelayed(1, 1000);
        int imageUrl = ResourceLink.getImageUrl();
        if (imageUrl != 0) {
            Picasso.with(this).load(imageUrl).into(ivBackground);
            handler.sendEmptyMessageDelayed(2, 5000);
        }
        handler.sendEmptyMessageDelayed(3, 5000);
        llyBottom.getBackground().setAlpha(180);
        userId = getIntent().getStringExtra(Constant.USER_ID);

        recordPermission = PermissionUtils.getInstance(this)
                .raPermission();
        locationPermission = PermissionUtils.getInstance(this).laPermission();
        sdPermission = PermissionUtils.getInstance(this).sdPermission();
        JrmfClient.setIUserAvatar(RpUserAvatar.getInstent());
        JMessageClient.registerEventReceiver(this);
    }

    @Override
    public void initListener() {

    }

    private void onListener() {
        mainHeartview.setOnClickListener(this);
        bottomChat.setOnClickListener(this);
        bottomUser.setOnClickListener(this);
        bottomFriend.setOnClickListener(this);
        bottomMap.setOnClickListener(this);
    }

    @Override
    public void initDate(MyIntent intent) {
        otherUid = userId.equals("111111") ? "222222" : "111111";
        MyApp.userId = userId;
//        String id = userId.equals("111111") ? "xz0011" : "222222";
//        LogUtil.e("tag","custUid+ "+id);
        MyApp.token = JrmfSignUtil.sign(userId + Constant.SECKEY);
        getOtherInfo();
        //获取位置
        getLocation();
        //刷新
        BitmapUtils.getInstance().upDateUserInfo();

    }

    private void setLoveTime() {
        //计算日期
        String together = DateUtils.getTogether("27-03-2018");
        animtv = AnimationUtils.loadAnimation(this, R.anim.animtvshow);
        if (StringUtil.isNotEmpty(together)) {
            mainTv1.setAnimation(animtv);
            mainTv.setAnimation(animtv);
            mainTv.setText(together);
            mainTv1.setText("在一起");
            explosionField.addListener(mainHeartview);
        }
    }

    /**
     * 获取好友信息
     */
    public void getOtherInfo() {
        ChatUserUtils.getOtherNickName(otherUid, new ChatUserUtils.UserNickNameCallback() {
            @Override
            public void gotResult(UserInfo userInfo) {
                if (userInfo != null) {
                    otherNickName = userInfo.getNickname();
                    otherAddress = userInfo.getAddress();
                    LogUtil.e("tag", "获取成功》》》》" + otherNickName + "位置》》》》" + otherAddress);
                    userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
                        @Override
                        public void gotResult(int i, String s, Bitmap bitmap) {
                            if (i == 0) {
                                BitmapUtils.getInstance().setoAvatar(bitmap);
                            }
                        }
                    });
                    MapActivity activity = ActivityManger.Companion.getInstance().findActivity(MapActivity.class);
                    if (activity != null) {
                        activity.setOtherMarks(otherAddress);
                    }
                }
            }

            @Override
            public void errMsg(String err) {
                handler.sendEmptyMessageDelayed(4, 3000);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_heartview:
                mainTv.setVisibility(View.GONE);
                mainTv1.setVisibility(View.GONE);
                break;
            case R.id.main_bottom_chat:  //聊天
                if (recordPermission) {
                    Intent intent = new Intent(this, ChatActivity.class);
                    intent.putExtra(Constant.USER_ID, userId);
                    intent.putExtra(Constant.OTHER_UID, otherUid);
                    intent.putExtra(Constant.OTHER_NICK_NAME, otherNickName);
                    startActivity(intent);
                } else {
                    recordPermission = PermissionUtils.getInstance(this).raPermission();
                }
                break;
            case R.id.main_bottom_user:  //用户设置
                Intent intent1 = new Intent(this, MyUserActivity.class);
                intent1.putExtra(Constant.USER_ID, userId);
                startActivity(intent1);
                break;
            case R.id.main_bottom_friend:  //好友
                startActivity(new Intent(this, MyFrienActivity.class));
                break;
            case R.id.main_bottom_map:
                if (locationPermission) {
                    startActivity(new Intent(this, MapActivity.class));
                } else {
                    locationPermission = PermissionUtils.getInstance(this).laPermission();
                }
                break;
        }
    }

    private void loadImage() {
        ivBackground.setAnimation(animtv);
        Picasso.with(this).load(ResourceLink.getImageUrl()).into(ivBackground);
    }

    private void simulationClick() {
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.heartrom);
        mainHeartview.setAnimation(animation);
        HeartFaomThread thread = new HeartFaomThread(this, heardFaom, 50);
        thread.start();
        mainTv1.setVisibility(View.GONE);
        mainTv.setVisibility(View.GONE);
        new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 4) {
                    mainHeartview.setVisibility(View.GONE);
                    onListener();
                }
            }
        }.sendEmptyMessageDelayed(4, 1500);

    }

    //接收聊天室消息
    public void onEventMainThread(ChatRoomMessageEvent event) {
        LogUtil.e("tag", "收到消息---");
        List<cn.jpush.im.android.api.model.Message> msgs = event.getMessages();
        for (cn.jpush.im.android.api.model.Message msg : msgs) {
            //这个页面仅仅展示聊天室会话的消息
            LogUtil.e("tag", "MessageReceived = " + msg.getId());
//            postMessageToDisplay("MessageReceived", event.getResponseCode(), event.getResponseDesc(), msg);
        }
    }

    PoputWindowUtils windowUtils;

    @Override
    protected void onResume() {
        super.onResume();
        windowUtils = PoputWindowUtils.getInstance();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (windowUtils != null) {
            windowUtils.destroy();
            windowUtils = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (windowUtils.popWinIsShow()) {
            windowUtils.dismissPopmenu();
        } else {
            windowUtils.showDefaultPopmenu(this, getWindow().getDecorView(), new PoputWindowUtils.OnMenuItemClickListener() {
                @Override
                public void onMenuItemClick(PoputWindowUtils.Type type) {
                    if (type == PoputWindowUtils.Type.default1) {
                        windowUtils.dismissPopmenu();
                        windowUtils = null;
                        finish();
                    } else {
                        if (windowUtils != null)
                            windowUtils.dismissPopmenu();
                    }
                }
            }, "退出", "取消");
        }
        return false;
    }

    /**
     * 获取位置
     */
    private void getLocation() {

        mlocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(LatlonUtils.getInstance(this));
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mlocationClient.startLocation();

        //起动服务 更新位置
        startService(new Intent(this, LatlonService.class));
    }


    public void onEvent(ContactNotifyEvent event) {
        String reason = event.getReason();
        String fromUsername = event.getFromUsername();
        String appkey = event.getfromUserAppKey();
        long createTime = event.getCreateTime();
        long eventId = event.getEventId();
        ContactNotifyEvent.Type type = event.getType();

        switch (type) {
            case invite_received://收到好友邀请
                LogUtil.e("tag", "收到好友邀请 = " + fromUsername + " >>>>> " + reason);
                FriendMsgLite bean = new FriendMsgLite();
                bean.setAppkey(appkey);
                bean.setCreateTime(createTime);
                bean.setId(eventId);
                bean.setFromUsername(fromUsername);
                bean.setRead(false);
                bean.setReason(reason);
                bean.setType(type);
                boolean save = bean.save();
                if (save) {
                    LogUtil.e("tag", "数据库数据保存成功》》》》》》");
                } else {
                    LogUtil.e("tag", "数据库数据保存失败》》》》》》");
                }
                break;
            case invite_accepted://对方接收了你的好友邀请
                //...
                break;
            case invite_declined://对方拒绝了你的好友邀请
                //...
                break;
            case contact_deleted://对方将你从好友中删除
                //...
                break;
            default:
                break;
        }
    }

    public void onEvent(LoginStateChangeEvent event) {
        LoginStateChangeEvent.Reason reason = event.getReason();//获取变更的原因
        UserInfo myInfo = event.getMyInfo();//获取当前被登出账号的信息
        switch (reason) {
            case user_password_change:
                //用户密码在服务器端被修改
                break;
            case user_logout:
                //用户换设备登录
                JMessageClient.logout();
                startActivity(new Intent(this, LoginActivity.class));
                ToastUtil.showLongToast(this, "账号在别处登录");
                ActivityManger.Companion.getInstance().finishAllActivity();
                break;
            case user_deleted:
                //用户被删除
                break;
        }
    }

    @Override
    protected void onDestroy() {
        JMessageClient.unRegisterEventReceiver(this);
        userId = "";
        otherUid = "";
        otherNickName = "";
        handler = null;
        //关闭服务
        stopService(new Intent(this, LatlonService.class));
        super.onDestroy();
    }
}
